import 'dart:io';
import 'dart:typed_data';

import 'package:ffmpeg_kit_flutter_new/ffmpeg_kit.dart';
import 'package:ffmpeg_kit_flutter_new/return_code.dart';

class RealtimePcmToWavConverter {
  final String outputPath;
  final int sampleRate;
  final int numChannels;
  final int bitsPerSample;

  late RandomAccessFile _wavFile;
  int _dataSize = 0;


  RealtimePcmToWavConverter({
    required this.outputPath,
    this.sampleRate = 44100,
    this.numChannels = 1,
    this.bitsPerSample = 16,
  }) {
    _initializeFile();
  }

  void _initializeFile() {
   // _wavFile = File(outputPath).open(mode: FileMode.writeOnlyAppend);
    File(outputPath).open(mode: FileMode.writeOnlyAppend).then((wavFile) {
      _wavFile = wavFile;
      // 写入初始占位头（全零）
      final placeholder = Uint8List(44);
      _wavFile.writeFrom(placeholder);
    });


  }

  void writeChunk(Uint8List pcmData) {
    if (_wavFile != null) {
      _wavFile.writeFrom(pcmData).then((wavFile) {
        _dataSize += pcmData.length;
      });

    }

  }

  void finalize() {
    // 计算最终文件大小
    final totalFileSize = 44 + _dataSize;
    _wavFile.setPosition(0).then((file) {
      _wavFile.writeFrom(_generateHeader(totalFileSize));

      // 此处将wav转换成mp3.
      FFmpegKit.execute('-i ${_wavFile.path} -codec:a libmp3lame -q:a 2 ${_wavFile.path.replaceAll('wav', 'mp3')}').then((session) async {
        final returnCode = await session.getReturnCode();
        if (ReturnCode.isSuccess(returnCode)) {
          // SUCCESS
          print('转换成功....');

        } else if (ReturnCode.isCancel(returnCode)) {
          // CANCEL
          print('转换取消....');
        } else {
          // ERROR
          print('转换错误....');
        }
      });


    });




  }

  // 辅助方法：生成标准WAV头（用于预验证）
  Uint8List _generateHeader(int dataSize) {
    final header = ByteData(44);

    // RIFF Chunk
    header.setUint32(0, 0x46464952, Endian.little); // "RIFF"
    header.setUint32(4, 36 + dataSize, Endian.little); // 文件总大小
    header.setUint32(8, 0x45564157, Endian.little); // "WAVE"

    // Format Chunk
    header.setUint32(12, 0x20746D66, Endian.little); // "fmt "
    header.setUint32(16, 16, Endian.little); // fmt块大小
    header.setUint16(20, 1, Endian.little); // PCM格式
    header.setUint16(22, numChannels, Endian.little);
    header.setUint32(24, sampleRate, Endian.little);
    header.setUint32(28, sampleRate * numChannels * (bitsPerSample ~/ 8),
        Endian.little);
    header.setUint16(32, numChannels * (bitsPerSample ~/ 8), Endian.little);
    header.setUint16(34, bitsPerSample, Endian.little);

    // Data Chunk
    header.setUint32(36, 0x61746164, Endian.little); // "data"
    header.setUint32(40, dataSize, Endian.little); // 数据大小

    return header.buffer.asUint8List();
  }
}

// 使用示例
void main() async {
  final converter = RealtimePcmToWavConverter(
    outputPath: 'live_output.wav',
    sampleRate: 16000,
    numChannels: 1,
  );

  // 模拟实时音频输入
  const duration = Duration(seconds: 5);
  final stopwatch = Stopwatch()..start();

  while (stopwatch.elapsed < duration) {
    // 生成模拟PCM数据（实际应从音频设备获取）
    final chunkSize = 16000 * 2; // 1秒@16kHz 16bit
    final pcmChunk = Uint8List.fromList(
        List.generate(chunkSize, (i) => i % 256));

    converter.writeChunk(pcmChunk);
    await Future.delayed(Duration(milliseconds: 100));
  }

  converter.finalize();
  print('实时转换完成！文件大小：${File('live_output.wav').lengthSync()} 字节');
}